package com.qiku.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiku.constants.SystemConstants;
import com.qiku.entity.Article;
import com.qiku.entity.Category;
import com.qiku.entity.ResponseResult;
import com.qiku.mapper.CategoryMapper;
import com.qiku.service.ArticleService;
import com.qiku.service.CategoryService;
import com.qiku.vo.CategoryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
implements CategoryService {

    @Autowired
    private ArticleService articleService;

    @Override
    public ResponseResult getCategoryList() {

        LambdaQueryWrapper<Article> articleWrapper = new LambdaQueryWrapper<>();
        articleWrapper.eq(Article::getStatus,SystemConstants.ARTICLE_STATUS_NORMAL);
        List<Article> articleList = articleService.list(articleWrapper);
        //获取文章的分类id 并去重
        Set<Long> categoryIds = articleList.stream().map(new Function<Article, Long>() {
            @Override
            public Long apply(Article article) {
                return article.getCategoryId();
            }
        }).collect(Collectors.toSet());
        //查询分类表
        List<Category> categoryList = listByIds(categoryIds);
        categoryList.stream().filter(new Predicate<Category>() {
            @Override
            public boolean test(Category category) {
                return SystemConstants.STATUS_NORMAL.equals(category.getStatus());
            }
        }).collect(Collectors.toList());
        List<CategoryVo> list = new ArrayList<>();
        for (Category category : categoryList){
            CategoryVo vo = new CategoryVo();
            BeanUtils.copyProperties(category,vo);
            list.add(vo);
        }

        return ResponseResult.okResult(list);
    }
}
